<template>
  <div class="app-container">
    <a-title @clickPreview="preview" />
    <el-form
      ref="queryForm"
      :model="queryParams"
      :inline="true"
      label-width="140px"
    >
      <el-form-item label="业务名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入业务名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="viewList"
        />
      </el-form-item>
      <el-form-item label="业务类别" prop="businessCategoryId">
        <el-cascader
          v-model="queryParams.businessCategoryId"
          :options="categoryOptions"
          :show-all-levels="false"
          :props="{ value: 'id', emitPath: false }"
          filterable
          style="width: 240px"
          placeholder="请选择业务类别"
        />
      </el-form-item>
      <el-form-item label="业务编号" prop="sectionNumber">
        <el-input
          v-model="queryParams.sectionNumber"
          placeholder="请输入业务编号"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="viewList"
        />
      </el-form-item>
      <el-form-item label="业务状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择业务状态"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option label="筹备" value="01" />
          <el-option label="进行中" value="02" />
          <el-option label="成果交付" value="03" />
          <el-option label="业务暂停" value="04" />
          <el-option label="业务终止" value="05" />
          <el-option label="业务完成" value="06" />
          <el-option label="作废" value="07" />
          <!--<el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />-->
        </el-select>
      </el-form-item>
      <el-form-item label="报告号/招标号" prop="searchReportNo">
        <el-input
          v-model="queryParams.searchReportNo"
          placeholder="请输入报告号/招标号"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="viewList"
        />
      </el-form-item>
      <el-form-item label="报告名称/标段名称" prop="searchReportName">
        <el-input
          v-model="queryParams.searchReportName"
          placeholder="请输入报告号/招标号"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="viewList"
        />
      </el-form-item>
      <el-form-item label="盖章日期">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          v-hasPermi="['project:business:list']"
          size="mini"
          @click="viewList"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="reset"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col v-if="isvalid && !isProjectMembers && closureStatus" :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleHistory"
         
        >业务操作历史记录</el-button>
        <!-- v-hasPermi="['project:business:historyList']"-->
      </el-col>
      <el-col :span="1.5">
        <div style="color:red;height: 28px;line-height: 28px;">如需新增业务，请联系您所在项目的项目负责人或者项目经理！</div>
      </el-col>
    </el-row>
    <div class="tablebox">
      <el-table
        stripe
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        :default-sort="{ prop: 'sectionNumber', order: 'descending' }"
        @sort-change="tableSortChange"
        :span-method="objectSpanMethod"
      >
        <el-table-column
          label="业务名称"
          align="left"
          prop="name"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
          min-width="230"
        />
        <el-table-column
          label="业务类别"
          align="center"
          prop="menuName"
          width="120"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        />
        <el-table-column
          label="业务编号"
          align="center"
          prop="sectionNumber"
          width="125"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        />
        <el-table-column
          label="业务状态"
          align="center"
          prop="status"
          width="100"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.statusType" disable-transitions>{{
              scope.row.statusText
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="归档状态"
          align="center"
          prop="archiveStatus"
          width="100"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.archiveStatusType" disable-transitions>{{
              scope.row.archiveStatusText
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="报告号/招标号"
          align="center"
          width="150"
          prop="agencyNo"
        >
        </el-table-column>

        <el-table-column
          label="报告名称/标段名称"
          align="left"
          prop="sectionName"
          min-width="230"
        >
        <template slot-scope="scope">
          <span v-if="scope.row.cancelStatus === '1' && !scope.row.agencyNo">

          </span>
          <span v-else>
           {{scope.row.sectionName}} 
          </span>
          
        </template>
        </el-table-column>

        <el-table-column
          label="盖章日期"
          align="center"
          width="120"
          prop="agencyStampTime"
        >
          <template scope="scope">
            {{ parseTime(scope.row.agencyStampTime, "{y}-{m}-{d} ") }}
          </template>
        </el-table-column>

        <el-table-column width="180" label="操作" align="center">
          <template slot-scope="scope">
            <a
              v-if="
                scope.row.cancelStatus === '0' &&
                scope.row.moveStatus === '0' &&
                isvalid &&
                scope.row.tenderMemberFlag === '1' &&
                scope.row.guid != null
              "
              @click="handleRoute(scope.$index, scope.row)"
            >
              <i class="el-icon-document aicon" />业务主页
            </a>
            <a
              v-if="
                scope.row.cancelStatus === '0' &&
                scope.row.moveStatus === '0' &&
                isvalid &&
                !isProjectMembers &&
                closureStatus &&
                scope.row.guid != null
              "
              @click="handleEdit(scope.$index, scope.row)"
            >
              <i class="el-icon-edit aicon" />编辑
            </a>
            <a
              v-if="scope.row.guid == null"
              @click="handleAdd(scope.$index, scope.row)"
            >
              <i class="el-icon-plus aicon" />历史数据迁移
            </a>
            <span v-if="scope.row.moveStatus === '1'" style="color: #999">
              业务迁移中
            </span>
            <a
              v-if="
                scope.row.cancelStatus === '0' &&
                scope.row.moveStatus === '0' &&
                closureStatus
              "
             
              @click="handleView(scope.$index, scope.row)"
            >
            <!-- v-hasPermi="['project:business:migration']"-->
              <i class="el-icon-copy-document aicon" />业务迁移
            </a>

            <a
              v-if="
                scope.row.cancelStatus === '0' &&
                scope.row.moveStatus === '0' &&
                closureStatus
              "
              v-hasPermi="['project:business:cancel']"
              @click="handleCancel(scope.$index, scope.row)"
            >
              <i class="el-icon-copy-document aicon" />作废
            </a>
            <a
              v-if="scope.row.cancelStatus === '1' && closureStatus"
              v-hasPermi="['project:business:cancel']"
              @click="handleCancelNew(scope.$index, scope.row)"
            >
              <i class="el-icon-copy-document aicon" />取消作废
            </a>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="viewList"
      />
    </div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="60%"
      @close="cancel"
    >
      <div class="tabletitle">
        <el-row :gutter="20">
          <el-col v-if="!isEdit" :span="12">
            <div class="input-wrap">
              <div class="input-label">
                <span class="mustinput">*</span>业务名称
              </div>
              <div class="input-content">
                <el-input v-model="project.name" placeholder="请输入" />
              </div>
            </div>
          </el-col>
          <el-col v-if="isEdit" :span="12">
            <div class="input-wrap">
              <div class="input-label">
                <span class="mustinput">*</span>业务名称
              </div>
              <div class="input-content">
                <el-input
                  v-model="project.name"
                  placeholder="请输入"
                  :disabled="!isEditBusinessName"
                />
              </div>
            </div>
          </el-col>
          <el-col v-if="!isEdit" :span="12">
            <div class="input-wrap">
              <div class="input-label">
                <span class="mustinput">*</span>业务类别
              </div>
              <div class="input-content">
                <el-cascader
                  v-model="project.businessCategoryId"
                  :options="categoryOptions"
                  :props="{ value: 'id', emitPath: false }"
                  filterable
                  clearable
                  style="width: 100%"
                  @change="getShowEngineeringBidding"
                />
              </div>
            </div>
          </el-col>
          <el-col v-if="isEdit" :span="12">
            <div class="input-wrap">
              <div class="input-label">
                <span class="mustinput">*</span>业务类别
              </div>
              <div class="input-content">
                <el-input
                  v-model="project.menuName"
                  placeholder="请输入"
                  :disabled="true"
                />
              </div>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <div class="input-wrap">
              <div class="input-label">
                <span class="mustinput">*</span>业务状态
              </div>
              <div class="input-content">
                <el-select v-model="project.status" placeholder="业务状态">
                  <!--<el-option
                    v-for="dict in statusOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />-->
                  <el-option label="筹备" value="01" />
                  <el-option label="进行中" value="02" />
                  <el-option label="成果交付" value="03" />
                  <el-option label="业务暂停" value="04" />
                  <el-option label="业务终止" value="05" />
                  <el-option label="业务完成" value="06" />
                </el-select>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="input-wrap">
              <div class="input-label">状态说明</div>
              <div class="input-content">
                <el-input v-model="project.statusRemark" placeholder="请输入" />
              </div>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <div class="input-wrap">
              <div class="input-label">
                <span class="mustinput">*</span>开始日期
              </div>
              <div class="input-content">
                <el-date-picker
                  v-model="project.businessStartTime"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                />
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div v-if="!isEdit" class="input-wrap">
              <div class="input-label">
                <span class="mustinput">*</span>归档模板
              </div>
              <div class="input-content">
                <el-select
                  v-model="project.archiveTemplateId"
                  placeholder="请输入归档模板"
                >
                  <el-option
                    v-for="item in docArchiveList"
                    :key="item.guid"
                    :label="item.templateName"
                    :value="item.guid"
                  />
                </el-select>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div v-if="isEdit" class="input-wrap">
              <div class="input-label">
                <span class="mustinput">*</span>归档模板
              </div>
              <div class="input-content">
                <el-select
                  v-model="project.archiveTemplateName"
                  placeholder="请输入归档模板"
                  :disabled="true"
                >
                  <el-option
                    v-for="item in docArchiveList"
                    :key="item.guid"
                    :label="item.templateName"
                    :value="item.guid"
                  />
                </el-select>
              </div>
            </div>
          </el-col>
        </el-row>

        <el-row v-show="isShow" :gutter="20">
          <el-col :span="12">
            <div class="input-wrap">
              <div class="input-label">
                <span class="mustinput">*</span>招标组组长
              </div>
              <div class="input-content">
                <el-select
                  v-model="project.tenderLeader"
                  placeholder="招标组组长"
                  @change="addTenderLeaderName"
                >
                  <el-option
                    v-for="item in memberList"
                    :key="item.userId"
                    :label="item.nickName"
                    :value="item.userId"
                  />
                </el-select>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="input-wrap">
              <div class="input-label">
                <span class="mustinput">*</span>招标组组员
              </div>
              <div class="input-content">
                <el-select
                  v-model="project.tenderMembers"
                  multiple
                  placeholder="招标组组员"
                  @change="addTenderMembers"
                >
                  <el-option
                    v-for="item in memberList"
                    :key="item.userId"
                    :label="item.nickName"
                    :value="item.userId"
                  />
                </el-select>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="sumbit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="业务迁移" :visible.sync="Visible" width="60%">
      <el-form
        ref="queryForm"
        :model="migrateParams"
        :rules="migrateRules"
        :inline="true"
        label-width="100px"
      >
        <el-form-item label="项目代码" prop="completeCode">
          <el-input
            v-model="migrateParams.completeCode"
            placeholder="请输入项目代码"
            clearable
            size="small"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="migrateList"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="tablebox">
        <el-table v-loading="loading" :data="migrateData" style="width: 100%">
          <el-table-column label width="55" align="center">
            <template slot-scope="scope">
              <el-radio v-model="templateSelection" :label="scope.row.guid"
                >&nbsp;</el-radio
              >
            </template>
          </el-table-column>
          <el-table-column label="项目代码" prop="code" />
          <!--<el-table-column label="项目名称" prop="name" />-->
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="Visible = false">取 消</el-button>
        <el-button type="primary" @click="migrate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 历史业务变更记录对话框 -->
    <el-dialog :title="historyTitle" :visible.sync="openHistory" width="80%">
      <el-form
        ref="queryHistoryForm"
        :model="queryHistoryParams"
        :inline="true"
        label-width="78px"
        @submit.native.prevent
      >
        <el-form-item label="业务名称" prop="businessName">
          <el-input
            v-model="queryHistoryParams.businessName"
            placeholder="请输入业务名称"
            clearable
            style="width: 240px"
            size="small"
            @keyup.enter.native="getHistoryList"
          />
        </el-form-item>

        <el-form-item label="业务编号" prop="businessNo">
          <el-input
            v-model="queryHistoryParams.businessNo"
            placeholder="请输入业务编号"
            clearable
            style="width: 240px"
            size="small"
            @keyup.enter.native="getHistoryList"
          />
        </el-form-item>

        <el-form-item label="操作类型" prop="operType">
        <el-select
          v-model="queryHistoryParams.operType"
          placeholder="请选择操作类型"
          clearable
          style="width: 240px"
          size="small"
        >
          <el-option label="业务新增" value="1" />
          <el-option label="业务修改" value="2" />
          <el-option label="业务作废" value="3" />
          <el-option label="业务迁移" value="4" />
          <el-option label="取消作废" value="5" />
          <el-option label="历史号迁移" value="6" />
          <el-option label="历史号还原" value="7" />
        </el-select>
      </el-form-item>

        <el-form-item label="操作人" prop="operPerson">
          <el-input
            v-model="queryHistoryParams.operPerson"
            placeholder="请输入操作人"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="getHistoryList"
          />
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="queryHistoryParams.historyDateRange"
            clearable
            size="small"
            style="width: 240px"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="字段名称" prop="fieldName">
          <el-input
          style="width: 240px"
            v-model="queryHistoryParams.fieldName"
            placeholder="请输入字段名称"
            clearable
            size="small"
            @keyup.enter.native="getHistoryList"
          />
        </el-form-item>
         <el-form-item label="原值" prop="initParams">
          <el-input
          style="width: 240px"
            v-model="queryHistoryParams.initParams"
            placeholder="请输入原值"
            clearable
            size="small"
            @keyup.enter.native="getHistoryList"
          />
        </el-form-item>
         <el-form-item label="现值" prop="newParams">
          <el-input
          style="width: 240px"
            v-model="queryHistoryParams.newParams"
            placeholder="请输入现值"
            clearable
            size="small"
            @keyup.enter.native="getHistoryList"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getHistoryList">查询</el-button>
          <el-button  icon="el-icon-refresh" size="mini" @click="resetHistory">重 置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="historyLoading"
        :data="historyList"
        :default-sort="{prop: 'operTime', order: 'descending'}"
        @sort-change="historyTableSortChange"
      >
        <el-table-column
          label="业务名称"
          align="center"
          prop="businessName"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        />
        <el-table-column
          label="业务编号"
          align="center"
          prop="businessNo"
          :sort-orders="['ascending', 'descending']"
          width="120"
          sortable="custom"
        />
         <el-table-column
          label="操作类型"
          align="center"
          prop="operType"
          width="120"
        />
        <el-table-column
          label="操作人"
          align="center"
          prop="operPerson"
          width="100"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        />
        <el-table-column
          label="操作时间"
          align="center"
          prop="operTime"
          width="100"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        />
        <el-table-column
          label="字段名称"
          align="center"
          prop="fieldName"
          width="120"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        />
        <el-table-column
          label="原值"
          align="center"
          prop="initParams"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        />
        <el-table-column
          label="现值"
          align="center"
          prop="newParams"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        />
      </el-table>
      <pagination
        v-show="totalHistory>0"
        :total="totalHistory"
        :page.sync="queryHistoryParams.pageNum"
        :limit.sync="queryHistoryParams.pageSize"
        @pagination="getHistoryList"
      />
    </el-dialog>
    <!-- 预览 -->
    <el-dialog :visible.sync="openPreview" width="80%">
      <iframe
        :src="manualPreviewUrl"
        frameborder="0"
        width="100%"
        height="700px"
      ></iframe>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
import {
  listBusinessManagement,
  updateBusinessManagement,
  migrateBusinessManagement,
  addBusinessManagement,
  getBusinessRoute,
  listDocArchive,
  isShowEngineeringBidding,
  migrationList,
  tenderList,
  businessTreeSelect,
  checkProject,
  checkBussinessNameSingle,
  getReportType,
  getNewAndOldProjectInfo,
  getReportTypeCounts,
  cancelBusiness,
  checkWorkflow,
  cancelInstance,
  listBusinessOper
} from "@/api/projectWorkbench/projectList/businessManagement";
import { listMember } from "@/api/projectWorkbench/projectList/member";
import { isProjectMembers } from "@/api/projectleader/projectGlance";
import { checkProjectStatus } from "@/api/projectWorkbench/projectGlance";
import aTitle from "@/components/Title";
export default {
  name: "BusinessManagement",
  components: { aTitle },
  data() {
    return {
      manualPreviewUrl: null,
      // 是否显示业务历史弹出层
      openHistory: false,
      historyTitle:'',
      historyLoading:false,
      totalHistory: 0,
      historyList:[],
      tenderLeaderName:'',
      tenderMemberNames:'',
      queryHistoryParams:{
        operType:undefined,
        operPerson:undefined,
        operTime:undefined,
        initParams:undefined,
        newParams:undefined,
        operPersonNo:undefined,
        businessName:undefined,
        projectId:undefined,
        fieldName:undefined,
        historyDateRange:[],
        businessNo:undefined
      },
      oldName:undefined,
      openPreview: false,
      isEdit: false,
      isShow: false,
      title: "",
      Visible: false,
      loading: true,
      total: 0,
      dialogVisible: false,
      tableData: [],
      project: {
        name: null,
        businessStartTime: null,
        archiveTemplateId: null,
        menuName: null,
        status: null,
        statusRemark: null,
        tenderLeader: null,
        tenderMembers: null,
        businessCategoryId: null,
      },
      categoryOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        businessCategoryId: undefined,
        name: undefined,
        status: undefined,
        projectId: undefined,
        sectionNumber: undefined,
        searchReportName: undefined,
        searchReportNo: undefined,
      },
      statusOptions: [],
      memberList: [],
      docArchiveList: [],
      rowSpanArr: [],
      migrateData: [],
      migrateParams: {
        completeCode: undefined,
      },
      templateSelection: "",
      businessRoutes: [],
      // 日期范围
      dateRange: [],
      businessId: null,
      businessName: null,
      businessCategory: null,
      businessCategoryId: null,
      isProjectMembers: false,
      //项目结项状态
      closureStatus: false,
      isvalid: false,
      migrateRules: {
        completeCode: [
          { required: true, message: "项目代码不能为空", trigger: "blur" },
        ],
      },
      isEditBusinessName: false,
    };
  },
  created() {
    this.queryParams.projectId = this.$route.params.id;
    this.viewList();
    this.getDicts("business_status").then((response) => {
      this.statusOptions = response.data;
    });
    businessTreeSelect(this.$route.params.id).then((res) => {
      if (res.code === 200) {
        this.categoryOptions = res.data;
      }
    });
    tenderList({ projectId: this.$route.params.id }).then((res) => {
      if (res.code === 200) {
        this.memberList = res.data;
      }
    });
    isProjectMembers({ projectId: this.$route.params.id }).then((res) => {
      if (res.code === 200) {
        var userName = JSON.parse(sessionStorage.getItem("userinfo") || {})
              .userName;
        if(userName=="tjecadmin"){
           this.isProjectMembers = false;
        }else{
           this.isProjectMembers = res.isProjectMembers;
        }
       
      }
    });
    this.isvalid = sessionStorage.getItem("isvalid") === "1" ? true : false;

    checkProjectStatus(this.$route.params.id).then((res) => {
      if (res.data) {
        this.closureStatus = true;
      }
    });
  },
  mounted() {
    document.title = document.getElementById("projectNameTitle").innerHTML;
  },
  methods: {
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (
        columnIndex === 0 ||
        columnIndex === 1 ||
        columnIndex === 2 ||
        columnIndex === 3 ||
        columnIndex === 4 ||
        columnIndex === 8
      ) {
        const _row = this.rowSpanArr[rowIndex];
        return {
          rowspan: _row, // 行
          colspan: _row > 0 ? 1 : 0, // 列
        };
      }
    },
    getRowSpan() {
      this.rowSpanArr = [];
      this.tableData.forEach((item, index) => {
        if (index == 0) {
          this.rowSpanArr.push(1);
          this.position = 0;
        } else {
          if (
            this.tableData[index].guid == this.tableData[index - 1].guid &&
            this.tableData[index].guid != null
          ) {
            this.rowSpanArr[this.position] += 1; //项目名称相同，合并到同一个数组中
            this.rowSpanArr.push(0);
            this.tableData[index].name = this.tableData[index - 1].name;
            this.tableData[index].menuName = this.tableData[index - 1].menuName;
            this.tableData[index].sectionNumber = this.tableData[
              index - 1
            ].sectionNumber;
            this.tableData[index].status = this.tableData[index - 1].status;
            this.tableData[index].archiveStatus = this.tableData[
              index - 1
            ].archiveStatus;
          } else {
            this.rowSpanArr.push(1);
            this.position = index;
          }
        }
      });
    },
    preview() {
      this.openPreview = true;
      this.manualPreviewUrl = `${this.previewUrl}${encodeURIComponent(
        `${this.operationManual}项目主页/业务系统操作说明-项目主页-业务管理.xlsx`
      )}&name=${encodeURIComponent("业务系统操作说明-项目主页-业务管理.xlsx")}`;
    },
    viewList() {
      // 查询业务列表
      this.loading = true;
      listBusinessManagement(
        this.addDateRange(this.queryParams, this.dateRange)
      ).then((res) => {
        if (res.code === 200) {
          this.total = res.total;
          this.tableData = res.rows.map((item) => {
            if (item.status === "01") {
              item.statusText = "筹备";
              item.statusType = "";
            } else if (item.status === "02") {
              item.statusText = "进行中";
              item.statusType = "info";
            } else if (item.status === "03") {
              item.statusText = "成果交付";
              item.statusType = "success";
            } else if (item.status === "04") {
              item.statusText = "业务暂停";
              item.statusType = "danger";
            } else if (item.status === "05") {
              item.statusText = "业务终止";
              item.statusType = "warning";
            } else if (item.status === "06") {
              item.statusText = "业务完成";
              item.statusType = "success";
            } else if (item.status === "07") {
              item.statusText = "作废";
              item.statusType = "danger";
            } else {
              item.statusText = "无";
              item.statusType = "info";
            }

            var userName = JSON.parse(sessionStorage.getItem("userinfo") || {})
              .userName;
            if(userName=="tjecadmin"){
              item.tenderMemberFlag = "1"
            }

            if (item.cancelStatus === "1") {
              //作废
              item.statusText = "作废";
              item.statusType = "danger";
            }

            if (item.archiveStatus === "0") {
              item.archiveStatusText = "未归档";
              item.archiveStatusType = "info";
            } else if (item.archiveStatus === "1") {
              item.archiveStatusText = "已归档";
              item.archiveStatusType = "success";
            } else if (item.archiveStatus === "2") {
              item.archiveStatusText = "归档中";
              item.archiveStatusType = "danger";
            } else {
              item.archiveStatusText = "无";
              item.archiveStatusType = "info";
            }
            return item;
          });
          this.getRowSpan();
          this.loading = false;
        }
      });
    },
    migrateList() {
      this.$refs["queryForm"].validate((valid) => {
        if (valid) {
          console.log("------------" + this.migrateParams.completeCode);
          migrationList(this.migrateParams).then((res) => {
            if (res.code === 200) {
              this.migrateData = res.data;
            } else {
              this.msgError(res.msg);
            }
          });
        }
      });
    },
    reset() {
      this.dateRange = [];
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 20;
      this.queryParams.name = undefined;
      this.queryParams.businessCategoryId = undefined;
      this.queryParams.status = undefined;
      this.queryParams.searchReportNo = undefined;
      this.queryParams.searchReportName = undefined;
      this.queryParams.sectionNumber = undefined;

      this.viewList();
    },
    getShowEngineeringBidding(val) {
      debugger
      this.project.archiveTemplateId = null;
      isShowEngineeringBidding(val).then((res) => {
        this.isShow = res.data;
        this.project.tenderLeader = null;
        this.project.tenderMembers = null;
      });
      listDocArchive(val).then((res) => {
        if (res.code === 200) {
          this.docArchiveList = res.data;
        }
      });
    },
    handleEdit(index, row) {
      this.isEdit = true;
      let newRow = JSON.parse(JSON.stringify(row));
      this.project = newRow;
      this.oldName = row.name;
      if (row && row.tenderMember) {
        var tenderMember = row.tenderMember.substr(
          0,
          row.tenderMember.lastIndexOf(";")
        );
        this.project.tenderMembers = tenderMember.split(";");
      }

      this.title = "编辑业务";
      isShowEngineeringBidding(row.businessCategoryId).then((res) => {
        this.isShow = res.data;
        this.dialogVisible = true;
      });
      getReportTypeCounts(row.guid).then((res) => {
        this.isEditBusinessName = false;
        var agencyNo = res.data.agencyNo;
        var reportNoApply = res.data.reportNoApply;
        var reportTypeCounts = res.data.reportTypeCounts;
        if (agencyNo == "" || agencyNo == null || agencyNo === undefined) {
          this.isEditBusinessName = true;
        }
        if (agencyNo && reportNoApply === "1" && reportTypeCounts > 1) {
          this.isEditBusinessName = true;
        }
      });
    },

    handleAdd(index, row) {
      this.isShow = false;
      this.isEdit = false;
      this.title = "添加业务";
      var agencyNo = "";
      var sectionName = "";
      var agencyStampTime = "";
      var tenderLeaderName = "";
      var tenderMemberNames = "";
      if (row) {
        var agencyNo = row.agencyNo;
        sectionName = row.sectionName;
        agencyStampTime = row.agencyStampTime;
        (this.project = {
          name: row.sectionName || null,
          businessStartTime: null,
          archiveTemplateId: null,
          menuName: null,
          status: "02",
          statusRemark: null,
          tenderLeader: null,
          tenderMembers: null,
          businessCategoryId: null,
          agencyNo: agencyNo,
          sectionName: sectionName,
          agencyStampTime: agencyStampTime,
        }),
          (this.dialogVisible = true);
      } else {
        (this.project = {
          name: sessionStorage.getItem("menuTitle") || null,
          businessStartTime: null,
          archiveTemplateId: null,
          menuName: null,
          status: "02",
          statusRemark: null,
          tenderLeader: null,
          tenderMembers: null,
          businessCategoryId: null,
          agencyNo: agencyNo,
          sectionName: sectionName,
        }),
          (this.dialogVisible = true);
      }
    },
    handleRoute(index, row) {
      if (row.status === "07") {
        this.msgError("作废状态的业务不能跳转到业务主页");
        return false;
      }
      getBusinessRoute(row.businessCategoryId).then((res) => {
        this.businessRoutes = res.data[0].children;
        this.businessRoutes.map((item) => {
          if (item.children) {
            item.children.map((obj) => {
              obj.name = obj.name
                .replace("/:id", "")
                .replace("/:businessCategoryId", "")
                .replace("/:projectId", "");
              obj.path =
                obj.path
                  .replace("/:id", "")
                  .replace("/:businessCategoryId", "")
                  .replace("/:projectId", "") +
                "/" +
                row.guid +
                "/" +
                row.businessCategoryId +
                "/" +
                this.$route.params.id;
              // obj.path = "businessWorkbench/businessList/" + obj.name.replace(obj.name[0], obj.name[0].toLowerCase()) + '/' + row.guid + '/' + row.businessCategoryId
            });
          } else {
            item.name = item.name
              .replace("/:id", "")
              .replace("/:businessCategoryId", "")
              .replace("/:projectId", "");
            item.path =
              item.path
                .replace("/:id", "")
                .replace("/:businessCategoryId", "")
                .replace("/:projectId", "") +
              "/" +
              row.guid +
              "/" +
              row.businessCategoryId +
              "/" +
              this.$route.params.id;
            // item.path = res.data[0].path + "/" + item.name.replace(item.name[0], item.name[0].toLowerCase()) + '/' + row.guid + '/' + row.businessCategoryId
          }
        });
        console.log(this.businessRoutes, "123");
        sessionStorage.setItem("menuBusinessTitle", row.name);
        sessionStorage.setItem("menuName", row.menuName);
        sessionStorage.setItem(
          "businessRoutes",
          JSON.stringify(this.businessRoutes)
        );
        /*if(sessionStorage.getItem("businessCategoryIds")){
           var typeIds = sessionStorage.getItem("businessCategoryIds")
           typeIds.push(row.businessCategoryId);
           typeIds.filter(function(item, index, typeIds) {
              //当前元素，在原始数组中的第一个索引==当前索引值，否则返回当前元素
              return typeIds.indexOf(item, 0) === index;
            });
            sessionStorage.setItem("businessCategoryIds",typeIds);
        }else{
           sessionStorage.setItem("businessCategoryIds",[row.businessCategoryId]);
        }*/
       
      });
      let routeData = this.$router.resolve({
        path: `/businessWorkbench/businessGeneral/${row.guid}/${row.businessCategoryId}/${this.$route.params.id}`,
      });
      setTimeout(function () {
        window.open(routeData.href, "_blank");
      }, 800);
    },
    sumbit() {
      debugger
      if (this.project.name === null || this.project.name.trim() === "") {
        this.msgError("业务名称不能为空");
        return false;
      }
      if (this.project.businessCategoryId === null) {
        this.msgError("业务类别不能为空");
        return false;
      }
      if (this.project.status === null) {
        this.msgError("业务状态不能为空");
        return false;
      }
      if (this.project.businessStartTime === null) {
        this.msgError("开始日期不能为空");
        return false;
      }
      if (this.project.archiveTemplateId === null) {
        this.msgError("归档模板不能为空");
        return false;
      }
      if (this.isShow && this.project.tenderLeader === null) {
        this.msgError("招标组组长不能为空");
        return false;
      }
      if (
        (this.isShow && this.project.tenderMembers === null) ||
        (this.isShow && this.project.tenderMembers.length == 0)
      ) {
        this.msgError("招标组组员不能为空");
        return false;
      }
      if (this.project.status === "01") {
        this.project.statusName = "筹备";
      } else if (this.project.status === "02") {
        this.project.statusName = "进行中";
      } else if (this.project.status === "03") {
        this.project.statusName = "成果交付";
      } else if (this.project.status === "04") {
        this.project.statusName = "业务暂停";
      } else if (this.project.status === "05") {
        this.project.statusName = "业务终止";
      } else if (this.project.status === "06") {
        this.project.statusName = "业务完成";
      } else if (this.project.status === "07") {
        this.project.statusName = "作废";
      }
      if (this.isEdit) {
        this.project.projectId = this.$route.params.id;
        var param = this.project;
        var $this = this;
        var checkParam = {
          name: $this.project.name,
          projectId: $this.$route.params.id,
        };

        var oldName = this.oldName;
        if(oldName && oldName != this.project.name){
          //检查名字是否重复
          checkBussinessNameSingle(checkParam).then((res) => {
            if (res.data === 0) {
              $this.updateBusinessManage(param);
            } else {
              this.msgError("业务名称已存在，请勿重复添加！");
            }
          });
        }else{
          $this.updateBusinessManage(param);
        }
       
      } else {
        this.project.projectId = this.$route.params.id;
        var param = this.project;
        var $this = this;
        var checkParam = {
          name: $this.project.name,
          projectId: $this.$route.params.id,
        };
        param.isShow = this.isShow;
        //检查名字是否重复
        checkBussinessNameSingle(checkParam).then((res) => {
          if (res.data === 0) {
            $this.addBusinessManage(param);
          } else {
            this.msgError("业务名称已存在，请勿重复添加！");
          }
        });
      }
    },
    updateBusinessManage() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
      });
      this.project.tenderLeaderName = this.tenderLeaderName;
      this.project.tenderMemberNames = this.tenderMemberNames;
      updateBusinessManagement(this.project).then((res) => {
        if (res.code === 200) {
          this.msgSuccess(res.msg);
          this.viewList();
          loading.close();
          this.dialogVisible = false;
        }
      });
    },
    addBusinessManage(param) {
      //如果不是招标类的业务
      //根据业务类别查找报告类型，如果有报告类型才可以绑定
      if (param.agencyNo) {
        if (param.isShow && param.agencyNo.substr(0, 5) != "H0701") {
          this.msgError(
            "【" + param.agencyNo + "】属于造价报告号，请选择造价咨询业务类别！"
          );
          return;
        }

        if (param.agencyNo.substr(0, 5) === "H0701" && !param.isShow) {
          this.msgError(
            "【" + param.agencyNo + "】属于招标代理号，请选择招标代理业务类别！"
          );
          return;
        } else {
          if (param.agencyNo.substr(0, 5) === "H0701" && param.isShow) {
            this.addBusinessManagementFinal(param);
          } else {
            var businessCategoryId = param.businessCategoryId;
            getReportType(businessCategoryId).then((res) => {
              if (res.code === 200) {
                if (res.msg) {
                  param.reportType = res.msg;
                  this.addBusinessManagementFinal(param);
                } else {
                  this.msgError(
                    "该业务类别无造价报告类型，请重新选择正确的业务类别！"
                  );
                  return;
                }
              } else {
                this.msgError("网络异常，请重新刷新页面！");
              }
            });
          }
        }
      } else {
        this.addBusinessManagementFinal(param);
      }
    },
    addBusinessManagementFinal(param) {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
      });
      debugger
      param.tenderLeaderName = this.tenderLeaderName;
      param.tenderMemberNames = this.tenderMemberNames;
      addBusinessManagement(param).then((res) => {
        if (res.code === 200 && res.data > 0) {
          this.msgSuccess(res.msg);
          this.viewList();
          loading.close();
          this.dialogVisible = false;
        } else {
          this.msgError("网络异常，请重新刷新页面！");
          loading.close();
        }
      });
    },
    migrate() {
      var newProjectId = this.templateSelection,
        oldProject = this.$route.params.id;
      if (!this.templateSelection) {
        this.msgError("请选择项目代码后再进行迁移！");
        return;
      }
      if (newProjectId && oldProject && oldProject === newProjectId) {
        this.msgError("迁移失败，原项目和迁移后项目不能相同！");
      }

      this.$confirm(
        "点击【确定】后将取消本业务下所有正在进行中的流程(包括申请号的流程), 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          cancelInstance(this.businessId);
          checkProject(this.templateSelection, this.businessId).then((res) => {
            if (res.data === 1) {
              //获取当前项目信息和新项目信息
              getNewAndOldProjectInfo(
                newProjectId,
                oldProject,
                this.businessId
              ).then((res) => {
                if (res && res.code === 200) {
                  res.data.businessId = this.businessId;
                  this.gotoBpm(res.data);
                }
              });
            } else {
              this.msgError(
                "迁移失败，本项目的服务范围不包含该业务的业务类别！"
              );
            }
          });
        })
        .catch(() => {});
    },
    gotoBpm(data) {
      var $this = this;
      var bpmUrl = this.bpmUrl;
      var rParam = {
        businessCategoryId: this.businessCategoryId,
        projectId: data.newProjectId,
        businessId: data.businessId,
        businessName: this.businessName,
        businessCategory: this.businessCategory,
        deptName: data.projectExecuteDept,

        projectLeader: data.oldProjectLeader,
        projectName: data.oldProjectName,
        projectCode: data.oldProjectCode,
        projectLeaderNo: data.oldProjectLeaderJobNo,

        newProjectLeader: data.newProjectLeader,
        newProjectName: data.newProjectName,
        newProjectCode: data.newProjectCode,
        newProjectLeaderNo: data.newProjectLeaderJobNo,
        bmsReport: data.bmsReport,
        bizObjectSchemaCode: "businessRemoval",
      };

      axios
        .post(bpmUrl + "/Portal/InstanceController/starInstance2", rParam)
        .then(function (response) {
          if (response.status == 200 && response.data) {
            var code = JSON.parse(sessionStorage.getItem("userinfo") || {})
              .jobNo;
              $this.Visible = false;
            window.open(
              bpmUrl +
                "/Portal/run.html?workflowCode=businessRemoval&formId=" +
                response.data.formId +
                "&date=" +
                response.data.date +
                "&code=" +
                code
            );
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    migrateSec() {
      this.$confirm(
        "执行此操作，本业务下的所有【进行中】流程将被终止, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          migrateBusinessManagement({
            projectId: this.templateSelection,
            guid: this.businessId,
          }).then((res) => {
            if (res.code === 200) {
              this.msgSuccess(res.msg);
              this.viewList();
              this.Visible = false;
            }
          });
        })
        .catch(() => {});
    },
    handleView(index, row) {
      this.Visible = true;
      this.businessId = row.guid;
      this.businessName = row.name;
      this.businessCategory = row.menuName;
      this.businessCategoryId = row.businessCategoryId;
      this.migrateData = [];
      // this.migrateList()
    },
    handleSelectionChange() {
      this.multiple = val;
    },
    tableSortChange(column) {
      this.queryParams.pageNum = 1;
      if (column.order === "descending") {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "desc";
      } else {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "asc";
      }
      this.viewList();
    },
    cancel() {
      this.dialogVisible = false;
    },
    handleCancel(index, row) {
      var $this = this;
      this.$confirm(
        "此操作将作废【" +
          row.name +
          "】业务，并取消本业务下所有进行中的流程, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          //if (row.agencyNo) {
          var reqParams = {
            businessCategoryId: row.businessCategoryId,
            guid: row.guid,
            projectId: this.$route.params.id
          };
          checkWorkflow(reqParams).then((res) => {
            if (res.code === 200) {
              if (res.msg === "0" || res.msg === "2") {
                //无流程
                var newData = {
                  guid: row.guid,
                  businessCategoryId: row.businessCategoryId,
                  name: row.name,
                  cancelStatus: "1",
                  agencyNo: row.agencyNo,
                  projectId: $this.$route.params.id
                };
                $this.cancelCheckBussinessNameSingle(newData);
              } else if (res.msg === "1") {
                //有流程
                $this.msgError("本业务下已有报告盖章流程，系统不支持作废！");
              }
            }
          });
          /*} else {
            var params = {
              guid: row.guid,
              businessCategoryId: row.businessCategoryId,
              name: row.name,
              cancelStatus: "1",
            };
            cancelBusiness(params).then((res) => {
              if (res.code === 200 && res.msg === "操作成功") {
                this.msgSuccess("操作成功！");
                this.viewList();
              } else {
                this.msgSuccess("操作失败！");
              }
            });
          }*/
        })
        .catch(() => {});
    },
    handleCancelNew(index, row) {
      var checkParam = {
        name: row.name.substr(4),
        projectId: this.$route.params.id,
      };
      //检查名字是否重复
      checkBussinessNameSingle(checkParam).then((res) => {
        if (res.data === 0) {
          var params = {
            guid: row.guid,
            businessCategoryId: row.businessCategoryId,
            name: row.name,
            cancelStatus: "0"
          };
          this.cancelBusinessBack(params);
        } else {
          this.msgError(
            "业务名称【" +
              checkParam.name +
              "】已存在，请修改重复的业务名称后再操作本业务！"
          );
        }
      });
    },
    cancelCheckBussinessNameSingle(data) {
      cancelBusiness(data).then((res) => {
        if (res.code === 200 && res.msg === "操作成功") {
          this.msgSuccess("操作成功！");
          this.viewList();
        } else {
          this.msgSuccess("操作失败！");
        }
      });
    },
    cancelBusinessBack(data) {
      data.projectId= this.$route.params.id;
      cancelBusiness(data).then((res) => {
        if (res.code === 200 && res.msg === "操作成功") {
          this.msgSuccess("操作成功！");
          this.viewList();
        } else {
          this.msgSuccess("操作失败！");
        }
      });
    },
      /** 业务操作历史记录 */
    handleHistory () {
      this.resetHistory()
      this.openHistory = true
      this.historyTitle = '业务操作历史记录';
      this.getHistoryList()
    },
    resetHistory () {
      this.queryHistoryForm = {
        nickName: undefined
      }
      this.queryHistoryParams.historyDateRange=[];
      this.resetForm('queryHistoryForm');
      this.getHistoryList();
    },
    /** 查询业务操作历史记录列表 */
    getHistoryList () {
      this.historyLoading = true
      let reqPrams = {
        operType: this.queryHistoryParams.operType,
        operPerson: this.queryHistoryParams.operPerson,
        initParams: this.queryHistoryParams.initParams,
        newParams: this.queryHistoryParams.newParams,
        businessName: this.queryHistoryParams.businessName,
        projectId: this.$route.params.id,
        fieldName: this.queryHistoryParams.fieldName,
        sortBy: this.queryHistoryParams.sortBy,
        order: this.queryHistoryParams.order
      } 

      if(this.queryHistoryParams.historyDateRange){
        reqPrams.beginTimeStart = this.queryHistoryParams.historyDateRange[0];
        reqPrams.endTimeEnd = this.queryHistoryParams.historyDateRange[1];
      }

      listBusinessOper(reqPrams).then(response => {
        this.historyList = response.rows;
        if(this.historyList){
          var items = this.historyList;
          items.forEach(item=>{
             item.operTime = this.renderTime(item.operTime);
             if(item.operType ==="1"){
                item.operType = "业务新增";
             }else if(item.operType ==="2"){
                item.operType = "业务修改";
             }else if(item.operType ==="3"){
                item.operType = "业务作废";
             }else if(item.operType ==="4"){
                item.operType = "业务迁移";
             }else if(item.operType ==="5"){
                item.operType = "取消作废";
             }else if(item.operType ==="6"){
                item.operType = "历史号迁移";
             }else if(item.operType ==="7"){
                item.operType = "历史号还原";
             }
          });
        }
        this.totalHistory = response.total
        this.historyLoading = false
      })
    },
    renderTime(date) {
      var dateee = new Date(date).toJSON();
      return new Date(+new Date(dateee) + 8 * 3600 * 1000)
        .toISOString()
        .replace(/T/g, " ")
        .replace(/\.[\d]{3}Z/, "");
    },
    addTenderLeaderName(val){
      this.tenderLeaderName = val ? this.memberList.find(ele => ele.userId === val).nickName : ''
    },
    addTenderMembers(val){
      if(val){
        var persons = [];
        val.forEach(item=>{
          persons.push(item ? this.memberList.find(ele => ele.userId === item).nickName : '');
        });
        this.tenderMemberNames=persons.join(";");
      }else{
        this.tenderMemberNames = '';
      }
      
    },historyTableSortChange(column) {
      debugger
      this.queryHistoryParams.pageNum = 1;
      if (column.order === "descending") {
        this.queryHistoryParams.sortBy = column.prop;
        this.queryHistoryParams.order = "desc";
      } else {
        this.queryHistoryParams.sortBy = column.prop;
        this.queryHistoryParams.order = "asc";
      }
      this.getHistoryList();
    }
  },
};
</script>
<style lang="scss" scoped>
.tabletitle {
  margin: 0 20px;
  .input-wrap {
    padding: 8px;
    display: flex;

    .input-label {
      min-width: 1em;
      max-width: 8em;
      color: rgba(0, 0, 0, 0.65);
      margin-right: 12px;
      display: flex;
      margin-top: 9px;
      flex: 0 0 90px;
      justify-content: flex-end;
    }

    .input-content {
      -webkit-box-flex: 1;
      flex-grow: 1;
      .el-select {
        width: 100%;
      }
    }
  }
}
.tablebox {
  height: 100%;
}
/deep/.el-table .cell {
  font-family: PingFangSC-Regular;
  color: rgba(0, 0, 0, 0.85);
  letter-spacing: 0;
  // text-align: center;
  a {
    font-family: PingFangSC-Regular;
    font-size: 14px;
    color: #1890ff;
    letter-spacing: 0;
    text-align: right;
    line-height: 14px;
    margin: 0 5px;
  }
}
/deep/.el-form-item--medium .el-form-item__content {
  line-height: 32px;
}

/deep/.el-form {
  .el-cascader--medium {
    .el-input--medium .el-input__inner {
      height: 32px;
      line-height: 32px;
    }
  }
}

</style>
